#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Script to parse test.guiguider file and extract FrontJson nodes.
Each node is saved as a separate JSON file in the 'json' directory.
"""

import json
import os
import sys


def process_child_nodes(child_list):
    """
    Recursively process child nodes and extract only name, id, type, text properties.
    """
    processed_list = []
    
    for child in child_list:
        # Extract required fields with null value check
        child_data = {}
        
        # Only add fields that have non-null values
        if child.get("name") is not None:
            child_data["name"] = child.get("name")
        if child.get("id") is not None:
            child_data["id"] = child.get("id")
        if child.get("type") is not None:
            child_data["type"] = child.get("type")
        if child.get("text") is not None:
            child_data["text"] = child.get("text")
        
        # Add title_text if it exists (needed for tab elements)
        if "title_text" in child and child.get("title_text") is not None:
            child_data["title_text"] = child.get("title_text")
        
        # Only add event if it's not empty
        if child.get("event"):
            child_data["event"] = child.get("event")
            
        # Recursively process child nodes if they exist in "list"
        if "list" in child:
            child_data["list"] = process_child_nodes(child["list"])
            
        # Recursively process child nodes if they exist in "child"
        if "child" in child:
            child_data["child"] = process_child_nodes(child["child"])
            
        processed_list.append(child_data)
    
    return processed_list


def parse_frontjson(input_file, output_dir):
    """
    Parse the guiguider file and save each FrontJson node to a separate JSON file.
    """
    try:
        with open(input_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        # Create output directory if it doesn't exist
        os.makedirs(output_dir, exist_ok=True)
        
        # Extract FrontJson array
        frontjson_data = data.get('FrontJson', [])
        
        # Process each node in Front    Json
        for node in frontjson_data:
            # Extract required fields with null value check
            node_data = {}
            
            # Only add fields that have non-null values
            if node.get("name") is not None:
                node_data["name"] = node.get("name")
            if node.get("id") is not None:
                node_data["id"] = node.get("id")
            if node.get("type") is not None:
                node_data["type"] = node.get("type")
            if node.get("text") is not None:
                node_data["text"] = node.get("text")

            # Only add event if it's not empty
            if node.get("event"):
                node_data["event"] = node.get("event")
            
            # Handle list of child nodes
            if "list" in node:
                node_data["list"] = process_child_nodes(node["list"])
            
            # Save to JSON file
            if "name" in node_data and node_data["name"]:
                output_file = os.path.join(output_dir, f'{node_data["name"]}.json')
                with open(output_file, 'w', encoding='utf-8') as f:
                    json.dump(node_data, f, ensure_ascii=False, indent=2)
        
        print(f"Successfully parsed {input_file} and saved nodes to {output_dir} directory")
    except FileNotFoundError:
        print(f"Error: File {input_file} not found.")
        sys.exit(1)
    except json.JSONDecodeError as e:
        print(f"Error: Failed to decode JSON from {input_file}: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)


if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("Usage: python parse_frontjson.py <input_file> <output_dir>")
        sys.exit(1)
    
    input_file = sys.argv[1]
    output_dir = sys.argv[2]
    
    parse_frontjson(input_file, output_dir)